package cnki.kg.algorithm;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ToSum {

    @Test
    public void test(){
        int[] arr=new int[]{1,2,4,7,3};
        int[] res=toSum(arr,3);
        for (int re : res) {
            System.out.println(re);
        }
    }

    public int[] toSum(int[] arr,int target){
        Map<Integer,Integer> mp=new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            int tmp=target-arr[i];
            if(mp.containsKey(tmp)){
                return new int[]{mp.get(tmp),i};
            }
            mp.put(arr[i],i);
        }
        return null;
    }
    @Test
    public void test2(){
        int[] arr=new int[]{3,2,4};
        int[] res=toSum2(arr,6);
        for (int re : res) {
            System.out.println(re);
        }
    }

    public int[] toSum2(int[] num,int target){
        int[] res=new int[2];
        HashMap<Integer,Integer> mp=new HashMap<>();
        for (int i = 0; i < num.length; i++) {
            int x=target-num[i];
            if(mp.containsKey(x)){
                return new int[]{mp.get(x),i};
            }
            mp.put(num[i],i);
        }

        return res;
    }
    @Test
    public void test3(){
        int[] arr=new int[]{3,2,4};
        int res=removeElement(arr,2);
        System.out.println(res);
    }
    public int removeElement(int[] nums, int val) {
        // 快慢指针
        int slowIndex=0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != val) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
        }
        return slowIndex;

    }
    @Test
    public void test4(){
        String tem="abc";
        reverseString(tem.toCharArray());
        System.out.println(tem);
    }
    public void reverseString(char[] s) {
        for (int i = 0,j=s.length-1; i < s.length/2; i++,j--) {
            char t=s[i];
            s[i]=s[j];
            s[j]=t;
        }
    }
    @Test
    public void reverseWords() {
        String s="  hello world  ";
        String[] s1 = s.split(" ");
        StringBuilder builder=new StringBuilder();
        for (int i = s1.length-1; i >=0; i--) {
            if(s1[i].equals("")) continue;
            builder.append(s1[i].trim()+" ");
        }
        String st= builder.toString().trim();
        System.out.println(st);
    }
}
